package org.rc.six;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author dokeeffe
 */
public class IndexerService {

    private IndexDao indexStore;

    /**
     * Constructor passed the writer
     * @param indexWriter 
     */
    public IndexerService(IndexDao indexWriter) {
        this.indexStore = indexWriter;
    }


    public void index(Collection<Document> docs) {
        for(Document doc : docs) {
            index(doc);
        }
    }

    public void index(Document doc) {
        if(doc.getDisplayName()!=null) {
            for(String term : tokenize(doc)) {
                if(term.length()>1) {
                    //only storing words 2 char or greater in index
                    Index idx = indexStore.getIndex(term);
                    idx.addDocument(term, doc);
                    indexStore.storeIndex(idx);
                }
            }
        }
    }


    /**
     * Return a Set of unique words in the document
     * @param doc
     * @return
     */
    protected Set<String> tokenize(Document doc) {
        Set<String> result = new HashSet<String>();
        if(doc.getDisplayName()!=null) {
           result.addAll(Arrays.asList(doc.getDisplayName().toLowerCase().split(" ")));
        }
        if(doc.getText()!=null) {
           result.addAll(Arrays.asList(doc.getText().toLowerCase().split(" ")));
        }
        return result;
    }

    /**
     * @param indexStore the indexStore to set
     */
    public void setIndexStore(IndexDao indexStore) {
        this.indexStore = indexStore;
    }
}
